package com.fy.fyai.controller;

import com.fy.fyai.common.config.MultiModelManager;
import com.fy.fyai.common.result.R;
import com.qcloud.cos.COSClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * MCP工具调用控制器
 * 提供前端用户与MCP服务器交互的接口
 * @author fwq
 * @date 2025-01-17
 */
@Tag(name = "MCP工具调用")
@Slf4j
@RestController
@RequestMapping("/mcp")
public class McpController {

    @Resource
    private ChatClient chatClient;

    @Resource
    private MultiModelManager multiModelManager;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    /**
     * 调用MCP服务器工具
     *
     * @return 工具调用结果
     */
    @Operation(summary = "获取所有MCP服务工具")
    @PostMapping("/getAllMcpTools")
    public R getAllMcpTools() {
        FunctionCallback[] functionCallbacks = toolCallbackProvider.getToolCallbacks();
        Map<String, String> toolMap = new HashMap<>();
        for (FunctionCallback functionCallback : functionCallbacks) {
            toolMap.put(functionCallback.getName(), functionCallback.getDescription());
        }
        return R.ok(toolMap);
    }

    /**
     * 使用指定模型进行对话
     *
     * @param question 问题
     * @param modelName 模型名称 (ollama 或 openai)
     * @return AI回复内容
     */
    @Operation(summary = "使用指定模型进行对话")
    @PostMapping("/chatWithModel")
    public R chatWithModel(@RequestParam String question,
                          @RequestParam(required = false, defaultValue = "ollama") String modelName) {
        try {
            // 获取指定的模型
            ChatModel selectedModel = multiModelManager.getModel(modelName);

            // 创建 ChatClient 并添加工具回调
            ChatClient chatClient = ChatClient.builder(selectedModel)
                    .defaultAdvisors(new SimpleLoggerAdvisor())
                    .defaultFunctions(toolCallbackProvider.getToolCallbacks())
                    .build();
            
            // 调用AI
            String response = chatClient.prompt()
                    .user(question)
                    .call()
                    .content();
            
            return R.ok(response);
        } catch (Exception e) {
            log.error("调用模型失败: {}", modelName, e);
            return R.no("调用模型失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有可用的模型列表
     *
     * @return 模型列表
     */
    @Operation(summary = "获取所有可用的模型列表")
    @GetMapping("/models")
    public R getAvailableModels() {
        return R.ok(multiModelManager.getAvailableModels());
    }
}
